﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VirginiaDecode.Models
{
    /// <summary>
    ///加密类 
    /// </summary>
    internal class Mycode
    {
        /// <summary>
        ///明文
        /// </summary>
        public string Plaint { get; set; }
        /// <summary>
        ///密文
        /// </summary>
        public string Cipher { get; set; }
        /// <summary>
        //密钥
        /// </summary>
        public string Key { get; set; }
        /// <summary>
        //解密方法
        /// </summary>
        public void Decode()
        {
            //ToDo 解密过程
            //得到密钥长度，按长度分配密钥
            int length = Key.Length;
            //转换字符串为数组
            char[] cipher = Cipher.ToCharArray();
            char[] key = Key.ToCharArray();
            char[] plaint = new char[Cipher.Length];
            //循环加密计算，将密文分组解密
            for (int i = 0; i < Cipher.Length; i++)
            {
                //判断小写
                if (cipher[i] >= 'a' && cipher[i] <= 'z')
                
                {
                    //将密文和对应密钥的值相减后，mod26
                    int temp = Transform(cipher[i]) - Transform(key[i % length]);
                    //去除负数
                    if (temp < 0) { temp = (temp + 26) % 26; }
                    else temp = temp % 26;
                    //将明文由数值形式变回小写字母，放回数组
                    char ch = Convert.ToChar(temp + 97);
                    plaint[i] = ch;
                }
                //判断大写
                else if (cipher[i] >= 'A' && cipher[i] <= 'Z')
                {
                    //将密文和对应密钥的值相加后，mod26
                    int temp = Transform(cipher[i]) - Transform(key[i % length]);
                    //去除负数
                    if (temp < 0) { temp = (temp + 26) % 26; }
                    else temp = temp % 26;
                    //将明文由数值形式变回大写字母，放回数组
                    char ch = Convert.ToChar(temp + 65);
                    plaint[i] = ch;
                }
                //保留空格，逗号，句号
                else if (cipher[i] == ' ')
                { char ch = Convert.ToChar(' '); plaint[i] = ch; }
                else if (cipher[i] == '.')
                { char ch = Convert.ToChar('.'); plaint[i] = ch; }
                else if (cipher[i] == ',')
                { char ch = Convert.ToChar(','); plaint[i] = ch; }
            }
            //返回明文
            Plaint = new string(plaint);
        }
        /// <summary>
        /// 返回指定字符，并赋值0-25的方法
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        private int Transform(char ch)
        {
            //小写字母的转化
            if (ch >= 'a' && ch <= 'z')
                return (ch - 'a');
            //大写字母的转化
            else if (ch >= 'A' && ch <= 'Z')
                return (ch - 'A');
            else return 0;
        }
    }
}